package com.itheima.fillter;

import com.alibaba.fastjson.JSON;
import com.itheima.config.ExThreadExtetns;
import com.itheima.entity.User;
import com.itheima.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class webFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest1, ServletResponse servletResponse1, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) servletRequest1;
        HttpServletResponse servletResponse = (HttpServletResponse) servletResponse1;
        log.info("我开始拦截了:{}", servletRequest);
        String requestURI = servletRequest.getRequestURI();
        String[] urls = {"/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"};
        boolean check = check(urls, requestURI);
        if (check) {
            log.info("循环放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (servletRequest.getSession().getAttribute("employee") != null) {
            log.info("登录放行，登录的id位:{}", servletRequest.getSession().getAttribute("employee"));
            ExThreadExtetns.setThreadLocal((Long) servletRequest.getSession().getAttribute("employee"));
            log.info("登录放行，ID是:{}", ExThreadExtetns.getGlobalThread());
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (servletRequest.getSession().getAttribute("user") != null) {
            log.info("登录放行,phong值是:{}", servletRequest.getSession().getAttribute("user"));
            User user = (User) servletRequest.getSession().getAttribute("user");
            Long id = user.getId();
            ExThreadExtetns.setThreadLocal(id);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        log.info("未登录");
        servletResponse.setContentType("text/json:charset=utf-8");
        servletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    @Override
    public void destroy() {
    }

    public boolean check(String[] urls, String requestURI) {
        AntPathMatcher apm = new AntPathMatcher();
        for (String url : urls) {
            boolean match = apm.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
